package main

import (
	"fmt"
	log "log/slog"
	"net"
)

type Server struct {
	listener net.Listener
	addr     string
}

func (srv *Server) start() {
	listener, err := net.Listen("tcp", srv.addr)
	if err != nil {
		log.Error(fmt.Sprintf("Failed to listen on tcp port %v", srv.addr))
		return
	}
	srv.listener = listener

	log.Info(fmt.Sprintf("listen on tcp port %v", srv.addr))
	srv.runLoop()
}

func (srv *Server) runLoop() {
	for {
		conn, err := srv.listener.Accept()
		if err != nil {
			log.Error(fmt.Sprintf("Failed to accept an incoming connection: %v", err))
			continue
		}

		go srv.handleConn(conn)
	}
}

func (srv *Server) handleConn(conn net.Conn) {
	c := newConnection(conn)
	c.serve()
}

func newServer(addr string) *Server {
	return &Server{
		addr: addr,
	}
}
